import httpService, { RequestParam } from './request';
import http from '@ohos.net.http';
import { fileManager } from "../utils/fileUtils"
import { strCaptions } from '../utils/recallInterface';
import { promptAction } from '@kit.ArkUI';

let GENERATION_URL =
  "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=24.20a377630ea894885020879cba7651d5.2592000.1737641855.282335-77367973"
// GENERATION_URL="http://192.168.227.230:5000/post-endpoint"
let TAG = "_:_ImageRecog"


export default class ImageRecogManager {
  private requestOptions: http.HttpRequestOptions = {}
  excludeList = ["没有SIM卡", "记录页面信息", "翻译本页面", "回顾相似页面","理解页面信息"]

  InitParam(imgstr) {
    let datastr = 'image=' + encodeURIComponent(imgstr) + '&language_type=ENG&detect_direction=true'
    this.requestOptions = {
      method: http.RequestMethod.POST,
      header: [{
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      }],
      extraData: datastr
    }
  }

  parseOCRResult(result): strCaptions {
    let TAG = "_:_[parseResultOCR]"
    // console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")){
      promptAction.showToast({"message":result,"duration":5000})
    }
    try {
      let resultj = JSON.parse(result)
      // console.log(TAG, "parse success ", resultj, JSON.stringify(resultj))
      let str = ""

      for (let wordsobj of resultj["words_result"]) {
        try {
          if (!this.excludeList.includes(wordsobj)) {
            str += wordsobj["words"] + " "
          }
        } catch (e) {
          console.error(TAG, "jsonparse err ", e, "at", JSON.stringify(wordsobj))
        }
      }
      console.log(TAG, "get fullstr success ", str)
      return {
        str: str, captions: resultj["words_result"]
      }
    } catch (e) {
      console.error(TAG, "parseResult", e)
      return result
    }
  }

  async OCR(imgstr): Promise<strCaptions> {
    this.InitParam(imgstr)
    return await httpService.requestMain(GENERATION_URL,this.requestOptions,(response)=>{return this.parseOCRResult(response)})
  }
}